1 module hip.concurrency.ring_buffer; 2 import hip.concurrency..volatile; 3 import hip.config.opts; 4 5 static if(HipConcurrency): 6 7 struct RingBuffer(T, uint Length) 8 { 9 import hip.concurrency..volatile; 10 @nogc: 11 12 T[Length] data; 13 private Volatile!uint writeCursor; 14 private Volatile!uint readCursor; 15 16 this() 17 { 18 this.writeCursor = 0; 19 this.readCursor = 0; 20 } 21 22 void push(T data) 23 { 24 this.data[writeCursor] = data; 25 writeCursor = (writeCursor+1) % Length; 26 } 27 ///It may read less than count if it is out of bounds 28 immutable T[] read(uint count) 29 { 30 uint temp = readCursor; 31 if(temp + count > Length) 32 { 33 readCursor = 0; 34 return data[temp..Length]; 35 } 36 readCursor = (temp+count)%Length; 37 return data[temp .. count]; 38 } 39 40 immutable T read() 41 { 42 uint temp = readCursor; 43 immutable T ret = data[temp]; 44 readCursor = (temp+1)%Length; 45 return ret; 46 } 47 48 void dispose() 49 { 50 data = null; 51 length = 0; 52 writeCursor = 0; 53 readCursor = 0; 54 } 55 56 ~this() 57 { 58 dispose(); 59 } 60 }